package com.chinastock.log;

import com.chinastock.Constant;
import com.chinastock.model.AppMessage;
import org.apache.logging.log4j.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import reactor.core.publisher.Flux;

import java.nio.charset.StandardCharsets;

/**
 * @author zhangfan.it
 * @date 2021/2/3
 */
public class ExtractBodyServerHttpRequestDecorator extends ServerHttpRequestDecorator {
    private static final Logger log = LoggerFactory.getLogger(LogName.BIZ);
    private static final String LOG_TYPE = "request";

    private final Flux<DataBuffer> body;

    public ExtractBodyServerHttpRequestDecorator(ServerHttpRequest delegate, String excludes, boolean isOn) {
        super(delegate);
        if (!isOn) {
            body = super.getBody();
        } else {
            body = super.getBody().map(dataBuffer -> {
                AppMessage appMessage = new AppMessage();
                appMessage.setUrl(delegate.getURI().getPath());
                MediaType type = delegate.getHeaders().getContentType();
                String typeStr = type == null ? "UnknownType" : type.getSubtype();
                appMessage.setContentType(typeStr);
                appMessage.setType(LOG_TYPE);
                appMessage.setHeaders(delegate.getHeaders().toSingleValueMap());
                appMessage.setObj(StandardCharsets.UTF_8.decode(dataBuffer.asByteBuffer()).toString());
                appMessage.setExcludes(excludes);
                log.info(appMessage.toString());
                return dataBuffer;
            });
        }
    }

    @Override
    public Flux<DataBuffer> getBody() {
        return body;
    }
}
